/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2020 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */

/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */

/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */
uint8_t rxData = 0;			// 用于缓冲串口接收的数据
uint8_t rs485_rxData = 0;

MODS_REG t_ModsReg;

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
static uint8_t REG_D01_Status(void)
{
	if(HAL_GPIO_ReadPin(LED0_GPIO_Port, LED0_Pin) == 1)
		return 0;
	else
		return 1;	
}

static uint8_t REG_D02_Status(void)
{
	if(HAL_GPIO_ReadPin(LED1_GPIO_Port, LED1_Pin) == 1)
		return 0;
	else
		return 1;	
}

static uint8_t REG_D03_Status(void)
{
	if(HAL_GPIO_ReadPin(BEEP_GPIO_Port, BEEP_Pin) == 1)
		return 1;
	else
		return 0;	
}

/* 注册回调函数 */
void MODS_REG_Attach(void)
{
	t_ModsReg.DXX_CB[REGID_D01] = REG_D01_Status;
	t_ModsReg.DXX_CB[REGID_D02] = REG_D02_Status;
	t_ModsReg.DXX_CB[REGID_D03] = REG_D03_Status;
}

/**
 * @brief		线圈状态检查
 * @param		status: 检查结果存放地址
 * @param		mods_reg: 回调函数结构体
 * @retval	None	
 * @note		本例程只有4个线圈,所以只会操作status[0]
 */
void MODS_REG_DXX_Check(uint8_t *status, MODS_REG *mods_reg)
{
	uint8_t i;
	uint8_t ret = 0;

	for(i=0; i<REGID_DXX; i++)
	{
		if(status[i / 8] & 0x01) LED0_ON; else LED0_OFF;
		if(status[i / 8] & 0x02) LED1_ON; else LED1_OFF;
		if(status[i / 8] & 0x04) BEEP_ENABLE(); else BEEP_DISABLE();
		
		// 存在对应回调函数
		if(mods_reg->DXX_CB[i])
		{
			// 执行函数
			ret = mods_reg->DXX_CB[i]();
			if(ret)
			{
				status[i / 8] |= (1 << i);		// 对应线圈的位置置1 
			}
		}
	}
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
  /* USER CODE BEGIN 1 */
	char *func = "Modbus RTU Mode with RS485 Interface Test!\n";
	uint8_t keyCode = 0;
	/* USER CODE END 1 */
  
  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init(); 

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
	bsp_InitHardBeep();
	bsp_InitKey();
	bsp_InitTimer();
  bsp_InitUsart();
  /* USER CODE BEGIN 2 */

	RS485_SendBuf((uint8_t *)func, strlen(func));

	HAL_UART_Receive_IT(&huart1, &rxData, 1);		// 接收1个字节就进入中断
	
	HAL_UART_Receive_IT(&huart2, &rs485_rxData, 1);		// 接收1个字节就进入中断

	MODS_REG_Attach();			// 注册回调函数
	/* USER CODE END 2 */
 
	bsp_StartAutoTimer(0, 10);	// 软件定时器10ms
	
  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		MODS_Poll();
		// 离散输入功能测试
		keyCode = bsp_GetKey();
		switch(keyCode)
		{
		case KEY_1_DOWN:
			REG_TXX_Status[0] |= 0x01;	
			break;

		case KEY_1_UP:
			REG_TXX_Status[0] &= ~0x01;	
			break;

		case KEY_2_DOWN:
			REG_TXX_Status[0] |= 0x02;	
			break;

		case KEY_2_UP:
			REG_TXX_Status[0] &= ~0x02;	
			break;

		case KEY_3_DOWN:
			REG_TXX_Status[0] |= 0x04;	
			break;

		case KEY_3_UP:
			REG_TXX_Status[0] &= ~0x04;	
			break;

		case KEY_4_DOWN:
			REG_TXX_Status[0] |= 0x08;	
			break;

		case KEY_4_UP:
			REG_TXX_Status[0] &= ~0x08;	
			break;
			
		default: 
			break;
		}
		
		// 10ms检查一次线圈状态
		if(bsp_CheckTimer(0) > 0)
		{
			Key_Scan();		// 按键扫描
			MODS_REG_DXX_Check(REG_DXX_Status, &t_ModsReg);
		}
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage 
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);
  /** Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 336;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }
  /** Initializes the CPU, AHB and APB busses clocks 
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }

  HAL_RCC_EnableCSS();

  HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq() / 1000);   // 1ms

  HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0); 		
}

/* USER CODE BEGIN 4 */
/* 串口接收完成回调函数 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *UartHandle)
{
	if(UartHandle == &huart1)
	{
		uint8_t ch;

		// 串口接收到的数据存入FIFO
		ch = rxData;
		g_tUart1.pRxBuf[g_tUart1.usRxWrite] = ch;
		if(++g_tUart1.usRxWrite >= g_tUart1.usRxBufSize)
		{
			g_tUart1.usRxWrite = 0;
		}
		if(g_tUart1.usRxCount < g_tUart1.usRxBufSize)
		{
			g_tUart1.usRxCount++;		// 还未从FIFO取出的数据自加
		}
		// 接收完要重新启动接收中断
		HAL_UART_Receive_IT(&huart1, &rxData, 1);			
	}

	if(UartHandle == &huart2)
	{
		uint8_t ch;

		// 串口接收到的数据存入FIFO
		ch = rs485_rxData;
		g_tUart2.pRxBuf[g_tUart2.usRxWrite] = ch;
		if(++g_tUart2.usRxWrite >= g_tUart2.usRxBufSize)
		{
			g_tUart2.usRxWrite = 0;
		}
		if(g_tUart2.usRxCount < g_tUart2.usRxBufSize)
		{
			g_tUart2.usRxCount++;		// 还未从FIFO取出的数据自加
		}
		
		// 485接收数据
		if(g_tUart2.ReveiveNew)
		{
			g_tUart2.ReveiveNew(ch);
		}
		
		// 接收完要重新启动接收中断
		HAL_UART_Receive_IT(&huart2, &rs485_rxData, 1);			
	}	
}

/* 串口发送完成回调函数 */
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *UartHandle)
{
	if(UartHandle == &huart1)
	{
		if(__HAL_UART_GET_IT_SOURCE(&huart1, UART_FLAG_TXE) != RESET)
		{
			if(g_tUart1.usTxCount == 0)
			{
				__HAL_UART_DISABLE_IT(&huart1, UART_IT_TXE);
				__HAL_UART_ENABLE_IT(&huart1, UART_IT_TC);
			}
			else
			{
				if(++g_tUart1.usTxRead >= g_tUart1.usTxBufSize)
				{
					g_tUart1.usTxRead = 0;
				}
				g_tUart1.usTxCount--;				
			}
		}
		else if(__HAL_UART_GET_IT_SOURCE(&huart1, UART_FLAG_TC) != RESET)
		{
			if(g_tUart1.usTxCount == 0)
			{
				__HAL_UART_DISABLE_IT(&huart1, UART_IT_TC);
			}
			else
			{
				// 一般不会进入到此else判断
				if(++g_tUart1.usTxRead >= g_tUart1.usTxBufSize)
				{
					g_tUart1.usTxRead = 0;
				}
				g_tUart1.usTxCount--;						
			}
		}
	}

	if(UartHandle == &huart2)
	{
		if(++g_tUart2.usTxRead >= g_tUart2.usTxBufSize)
		{
			g_tUart2.usTxRead = 0;
		}
		g_tUart2.usTxCount--; 
		if(g_tUart2.usTxCount == 0)
		{	
			// 回调函数，RS485发送完成后将芯片设为接收模式	
			if(g_tUart2.SendOver)
			{
				g_tUart2.SendOver();
			}			
		}
		
#if 0	 // 调试时程序不执行g_tUart2.usTxCount--;	原因未知 代码被优化*
		if(__HAL_UART_GET_IT_SOURCE(&huart2, UART_FLAG_TXE) != RESET)
		{
			if(g_tUart2.usTxCount == 0)
			{
				__HAL_UART_DISABLE_IT(&huart2, UART_IT_TXE);
				__HAL_UART_ENABLE_IT(&huart2, UART_IT_TC);
			}
			else
			{
				if(++g_tUart2.usTxRead >= g_tUart2.usTxBufSize)
				{
					g_tUart2.usTxRead = 0;
				}
				g_tUart2.usTxCount--;			
			}
		}
		else if(__HAL_UART_GET_IT_SOURCE(&huart2, UART_FLAG_TC) != RESET)
		{
			if(g_tUart2.usTxCount == 0)
			{
				__HAL_UART_DISABLE_IT(&huart2, UART_IT_TC);
				// 回调函数，RS485发送完成后将芯片设为接收模式	
				if(g_tUart2.SendOver)
				{
					g_tUart2.SendOver();
				}
			}
			else
			{
				// 一般不会进入到此else判断
				if(++g_tUart2.usTxRead >= g_tUart2.usTxBufSize)
				{
					g_tUart2.usTxRead = 0;
				}
				g_tUart2.usTxCount--;						
			}
		}
#endif
	}	
	
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */

  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{ 
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     tex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
